#include "dialog.h"
#include "ui_dialog.h"
#include "modbus_uart.h"

#include <qmessagebox.h>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    ui->numline->setValidator(new QIntValidator(1, 1968, this));
    ui->addrline->setValidator(new QIntValidator(1,247, this));
    ui->startaddrline->setValidator(new QIntValidator(0, 65535, this));
//    ui->check->setDisabled(true);
    ui->over->setDisabled(true);


    //限制起时地址
    connect(ui->addrline,&QLineEdit::textChanged,[=](){
        if(ui->addrline->text().toInt()>247||ui->addrline->text().toInt()<1)
        {
            QMessageBox::warning(this,"提示","请检查起时地址和数量是否合法！",QMessageBox::Ok,QMessageBox::NoButton);
            ui->addrline->clear();
        }
    });

    connect(ui->numline,&QLineEdit::textChanged,[=](){
        if(ui->numline->text().toInt()+ui->startaddrline->text().toInt()>65536)
        {
            QMessageBox::warning(this,"提示","请检查起时地址和数量是否合法！",QMessageBox::Ok,QMessageBox::NoButton);
            ui->numline->clear();
        }
    });

    connect(ui->startaddrline,&QLineEdit::textChanged,[=]{
       if(ui->startaddrline->text().toInt()>65535)
       {
            QMessageBox::warning(this,"提示","请检查起时地址是否合法！",QMessageBox::Ok,QMessageBox::NoButton);
            ui->startaddrline->clear();
       }
    });

    connect(ui->numline,&QLineEdit::textChanged,[=]{
       if(ui->numline->text().toInt()>1968||ui->numline->text().toInt()<1)
       {
            QMessageBox::warning(this,"提示","请检查起时地址是否合法！",QMessageBox::Ok,QMessageBox::NoButton);
            ui->numline->clear();
       }
    });
    inittable();
}

Dialog::~Dialog()
{
    delete ui;
}


void Dialog::inittable()
{
    //设置表格
    QStringList TableHeader;
    TableHeader << "地址" << "数据";
    ui->tablecoil->setHorizontalHeaderLabels(TableHeader);
    ui->tablecoil->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

//表格初始化
QByteArray Dialog::getUserInputData()
{
    return bamsg;
}

//表格数据初始化
void Dialog::tabledatainit(quint16 BeginAddress,quint16 Number)
{
    ui->tablecoil->clear();
    inittable();
    for(quint16 i = BeginAddress,k=0;k<Number; i++,k++)
    {
        //地址设置
        QString adr =  "0x" + QString("%1").arg(i,4,16,QLatin1Char('0'));
        ui->tablecoil->setItem(k,0, new QTableWidgetItem(adr.toUpper()));
        ui->tablecoil->item(k,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tablecoil->item(k,0)->setFlags(Qt::ItemIsEditable);
        //在线圈数据表中显示数据
        ui->tablecoil->setItem(k,1,new QTableWidgetItem(QString("%1").arg(initdata[k])));
        //设置表格内文字水平+垂直对齐
        ui->tablecoil->item(k,1)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    }
}


QVector<quint16> Dialog::infdata()
{
    quint16 addr = ui->addrline->text().toInt();
    quint16 num = ui->numline->text().toInt();
    inf.push_back(addr);
    inf.push_back(oldstartaddr);
    inf.push_back(num);
    return inf;
}



//双击单元格
void Dialog::on_tablecoil_cellDoubleClicked(int row, int column)
{
    QString cur;
    if(!(ui->tablecoil->item(row,1)==NULL))
    {
        cur=ui->tablecoil->item(row,1)->text();
    }
    else
    {
        cur="0";
    }
    edit=new QLineEdit;
    edit->setText(cur);
    QRegExp rx("[01]");
    QRegExpValidator *pReg = new QRegExpValidator(rx, this);
    edit->setValidator(pReg);
    ui->tablecoil->setCellWidget(row,1,edit);
    isfc=1;
    isclicked=1;
}

//单元格改变
void Dialog::on_tablecoil_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
    if(isfc==1)
    {
        pre=edit->text();
    }
    if(isclicked==1)
    {
        isfc=0;
        ui->tablecoil->setCellWidget(previousRow, 1,NULL);
        ui->tablecoil->setItem(previousRow,1,new QTableWidgetItem(pre));
    }
    isclicked=0;
}


//开始设置
void Dialog::on_start_btn_clicked()
{
    quint16 satrtaddr = ui->startaddrline->text().toInt();
    oldstartaddr = satrtaddr;
    quint16 num = ui->numline->text().toInt();
    quint16 addr = ui->addrline->text().toInt();
    if(num==0||addr==0)
    {
        QMessageBox::warning(this,"错误","输入阈值中的数据");
    }
    else if(satrtaddr+num-1>65535||num>1968)
    {
        QMessageBox::warning(this,"错误","输入阈值中的数据");
    }
    else
    {
        tabledatainit(satrtaddr,num);
        ui->start_btn->setDisabled(true);
//        ui->check->setDisabled(false);
        ui->over->setDisabled(false);           //使能关闭
        ui->addrline->setDisabled(true);
        ui->numline->setDisabled(true);
    }
}

//设置完成
void Dialog::on_over_clicked()
{
    quint16 addr = ui->addrline->text().toInt();
    quint16 num = ui->numline->text().toInt();


    if(num==0||addr==0||ui->start_btn->isEnabled())
    {
        QMessageBox::warning(this,"错误","输入阈值中的数据");
    }
    else
    {
        ui->start_btn->setDisabled(false);
        ui->addrline->setDisabled(false);
        ui->numline->setDisabled(false);
        ui->over->setDisabled(true);
 //       ui->check->setDisabled(true);
        GetData0X01(bamsg,oldstartaddr,num);
    }
}


//字节反转函数
void Dialog::byteReverse(QString &coils)
{
    // 定义临时字符变量
    QChar temp;

    for(int i=0; i < 4; i++)
    {
        temp = coils[i];        // 将第i个元素存入临时字符变量
        coils[i] = coils[8-i-1];  // 将第i个字符元素和第n-i-1个元素对调
        coils[8-i-1] = temp;    // 将临时字符变量的值赋给第n-i-1个元素
    }
}

//封装成字节
void Dialog::GetData0X01(QByteArray &coilsDataArr,quint16 BeginAddress,quint16 Number)
{
    //声明读取的数据字符串
    QString getDataString;
    quint8 responseMessageByteNum;
    //求响应报文字节数
    responseMessageByteNum = (quint8)((Number + 7) / 8);

    //从数据表中读取需要数量的线圈数据,形成二进制形式字符串
    for(quint16 i = 0; i < Number; i++)
    {
        //读出线圈数据
        QString buffer = ui->tablecoil->item(i,1)->text();
        if(buffer == "1")
        {
            getDataString += "1";
        }
        else
        {
            getDataString += "0";
        }
    }
    //二进制字符串补0
    for(int i = 1; i <= (8*responseMessageByteNum - Number); i++)
    {
        getDataString += "0";
    }
    //coilsDataArr.resize(responseMessageByteNum);
    //将二进制字符串按字节填入响应报文数组
    for(int i = 0; i < responseMessageByteNum; i++)
    {
        //对8位1字节进行反转处理
        QString buffer = getDataString.mid((8 * i),8);
        //字节反转
        byteReverse(buffer);
        //存入响应报文数组
        coilsDataArr[i] = buffer.toInt(NULL,2);
    }
    //qDebug()<<coilsDataArr;
    QMessageBox::information(this,"提示","设置完成！");
}
